package spring.convert;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class LocalDateTimeParameterConvert implements Converter<String, LocalDateTime> {

    @Override
    public LocalDateTime convert(String s) {
        if (StrUtil.isBlank(s)) {
            return null;
        }
        if (s.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
            return DateUtil.parseLocalDateTime(s.trim(), DatePattern.NORM_DATE_PATTERN);
        }
        if (s.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
            return DateUtil.parseLocalDateTime(s.trim());
        }
        try {
            return LocalDateTimeUtil.of(DateUtil.parse(s.trim()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Invalid value '" + s + "'");
        }
    }
}
